package org.echarts.servlet;

import org.codehaus.jackson.map.ObjectMapper;
import org.echarts.bean.Point;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取大量坐标数据
 * Created by Administrator on 2017/1/24.
 */
@WebServlet(name="GetPoints", urlPatterns = {"/getPoints"})
public class GetPoints extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String start = req.getParameter("start");
        String end = req.getParameter("end");
        if(start != null &&!start.equals("") && end !=null && !end.equals("")){
            List<Point> points = new ArrayList<>();

            Connection con = null;
            PreparedStatement ps = null;
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orclgbk", "huaat_bigdata", "huaat_bigdata");
                ps = con.prepareStatement("SELECT * FROM (SELECT A.*, rownum r FROM (SELECT * FROM TB_B_STATION) A WHERE rownum < " + end + ") B WHERE r > " + start);
                ResultSet rs = ps.executeQuery();
                while (rs.next()){
                    double lng = rs.getDouble("BD_LNG");
                    double lnt = rs.getDouble("BD_LAT");
                    Point point = new Point(lng, lnt);
                    points.add(point);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ps.close();
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            // 创建返回的json对象
            ObjectMapper mapper = new ObjectMapper();
            String points_json = mapper.writeValueAsString(points);

            //System.out.println(points_json);

            // 返回
            PrintWriter out = resp.getWriter();
            out.print(points_json);
        }


    }
}
